package cn.ulyer.common.security;

import cn.ulyer.common.jpa.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

@Getter
@Setter
public class LoginUser extends User implements UserDetails {


    private String token;


    Set<String> permissions;


    public boolean hasPermission(String role) {
        return permissions != null && permissions.contains(role);
    }



    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(permissions==null){
            return new HashSet<>();
        }
        List<GrantedAuthority> authorities=  permissions.stream().map(r->new SimpleGrantedAuthority(r)).collect(Collectors.toList());
        return authorities==null?new HashSet<>(): authorities;
    }



    @Override
    public boolean isAccountNonExpired() {
        return isCredentialsNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return getAccountLocked()==null||getAccountLocked()==0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
         return getExpireTime()==null||getExpireTime().after(new Date()) ;
    }

    @Override
    public boolean isEnabled() {
        return getEnable() == 1;
    }
}
